<!-- 使用 type="home" 属性设置首页，其他页面不需要设置，默认为page；推荐使用json5，更强大，且允许注释 -->
<route lang="json5">
{
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '购物车',
    navigationBarRightButton: {
      hide: true,
    },
  },
}
</route>
<template>
  <!-- page-meta 只能是页面内的第一个节点 -->
  <page-meta :page-style="`overflow:${popupShow ? 'hidden' : 'visible'};`"></page-meta>
  <view
    class="w-full h-full bg-white overflow-hidden box-border"
    :style="{ paddingTop: safeAreaInsets?.top + 'px' }"
  >
    <view class="w-full h-full pos-relative z-1">
      <wd-navbar>
        <template #title>
          <text class="text-gray-333 font-size-36 font-500">购物车</text>
        </template>
      </wd-navbar>

      <view class="w-full head-bg" :style="{ marginTop: safeAreaInsets?.top + 'px' }"></view>
      <view class="w-full p-x-28 p-y-32 box-border pos-relative home-content">
        <view
          class="w-full flex justify-start product-card"
          v-for="(item, index) in productList"
          :key="index"
          @longpress="longPress(item.good_id)"
        >
          <!-- v-if="checkedKeys.length > 0" -->
          <view class="flex justify-between flex-items-center">
            <view class="flex justify-center flex-items-center">
              <!-- <view
                class="w-full h-full bg-cover bg-no-repeat"
                v-if="checkedKeys.includes(item.good_id)"
              >
                <image width="100%" height="100%" :src="checkImage" /> 
              </view> -->
              <wd-checkbox v-model="item.checked" @change="checkChange"></wd-checkbox>
            </view>
          </view>
          <view class="wr-220 hr-220 pos-relative">
            <image width="100%" height="100%" :src="item.pic" />
            <view
              class="pos-absolute pos-bottom-0 pos-left-0 w-full hr-48 bg-black-1 text-white flex justify-center flex-items-center"
              v-if="false"
            >
              <text class="font-size-24 line-height-none">商品已下架</text>
            </view>
          </view>
          <view class="flex justify-between flex-col product-info">
            <view class="font-size-28 text-gray-333 font-500">{{ item.name }}</view>
            <view
              class="flex justify-between flex-items-center product-type font-size-24"
              v-if="item.sku_id"
              @click="openModel(item, index)"
            >
              <view>{{ item.sku_name }}</view>
              <wd-icon name="arrow-down" size="22rpx"></wd-icon>
            </view>
            <view class="flex justify-between flex-items-end">
              <view class="flex justify-start items-end" v-if="item.sku_id">
                <view class="font-size-24 line-height-none text-red-1 mg-r-4">¥</view>
                <view class="font-size-32 line-height-none text-red-1">{{ item.price }}</view>
              </view>
              <view v-if="item.buy_count > 0 || item.sku_id">
                <wd-input-number v-model="item.buy_count" @change="handleChange" />
              </view>
            </view>
            <view
              class="flex justify-between items-center"
              v-if="!item.sku_id && item.buy_count == 0"
            >
              <view class="font-size-24 line-height-none">请重新选择商品规格</view>
              <view class="hr-46">
                <wd-button plain size="small" @click="openModel(item, index)">重选</wd-button>
              </view>
            </view>
          </view>
        </view>
        <view
          class="w-full flex justify-between flex-items-center pos-absolute pos-bottom-0 pos-left-0 p-x-28 p-y-16 box-border"
        >
          <view class="flex justify-between items-center">
            <wd-checkbox v-model="checkedAll" @change="handleCheckAll"></wd-checkbox>
            <view class="font-size-28">全选</view>
          </view>
          <view class="flex justify-start flex-items-center">
            <view class="mg-r-12 font-size-28">合计</view>
            <view class="flex justify-start flex-items-center">
              <view class="font-size-24 line-height-none mg-r-6">¥</view>
              <view class="font-size-36 line-height-none mg-r-24">{{ priceAll }}</view>
            </view>
            <view class="wr-168 hr-80">
              <wd-button type="primary" size="small" @click="buyProduct">去结算</wd-button>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
  <wd-overlay :zIndex="1000" :show="overlayShow" @click="overlayShow = false">
    <view class="w-full h-full flex justify-center flex-items-center">
      <view
        class="wr-240 hr-80 bg-#fff flex justify-start flex-items-center ps-l-24"
        v-for="(item, index) in menuList"
        :key="index"
        @click="openDelete(item.name)"
      >
        <text>{{ item.name }}</text>
      </view>
    </view>
  </wd-overlay>
  <wd-popup
    v-model="popupShow"
    lock-scroll
    position="bottom"
    :safe-area-inset-bottom="true"
    @close="closePopup"
  >
    <view class="w-full hr-948">
      <view class="w-full h-full p-x-28 p-y-32 border-box pos-relative">
        <view
          class="pos-absolute pos-top-28 pos-right-32 z-1 font-size-28 font-500 text-gray-999"
          @click="closePopup"
        >
          <wd-icon name="close"></wd-icon>
        </view>
        <view class="flex justify-start">
          <view class="wr-176 hr-176">
            <image width="100%" height="100%" :src="productInfo?.pic" />
          </view>
          <view class="flex justify-end flex-col mg-l-28">
            <view class="flex justify-start items-end font-500 line-height-none text-red-1">
              <view class="font-size-24 mg-r-6 mg-b-6">¥</view>
              <view class="font-size-40 text-red-1">{{ productInfo?.price }}</view>
            </view>
            <view>
              <view class="text-gray-999 font-size-24 font-400 mg-t-32">
                库存 {{ productInfo?.storage }}
              </view>
              <view class="text-gray-333 font-size-28 font-400 mg-t-24">
                已选 {{ buyProductItem?.skuValue }}
              </view>
            </view>
          </view>
        </view>
        <view v-for="(item, index) in scalesList" :key="index">
          <view>
            <view class="font-size-32 font-500 text-gray-333 mg-t-28">{{ item.name }}</view>
            <view class="flex justify-start flex-wrap mg-t-32">
              <view
                v-for="(spec, index) in item?.list"
                :key="index"
                class="flex justify-center items-center p-x-32 p-y-16 b-rd-34 bg-#F3F4F8 text-gray-333 mg-b-20 mg-r-20"
                :class="{ 'bg-blue-1 text-white': spec.id == buyProductItem?.id }"
                @click="selectBuyProduct(spec)"
              >
                <text class="font-size-28 font-500">{{ spec.title }}</text>
              </view>
            </view>
          </view>
          <view class="flex justify-between items-center mg-t-40">
            <view class="font-size-32 font-500 text-gray-333">数量</view>
            <view>
              <wd-input-number v-model="proCount" @change="handleChange" />
            </view>
          </view>
        </view>
        <view
          class="w-full pos-absolute pos-bottom-28 pos-left-0 z-1 box-border pb-safe flex justify-center items-center p-x-28"
        >
          <!-- <view
              class="w-full hr-80 flex justify-center items-center font-size-32 text-gray-333 font-500 bg-#DFDFFF br-left"
              @click="addToCart"
            >
              加入购物车
            </view> -->
          <view
            class="w-full hr-80 flex justify-center items-center bg-#7195F8"
            @click="sureSelect"
          >
            <text class="font-size-32 text-white font-500">确认选择</text>
          </view>
        </view>
      </view>
    </view>
  </wd-popup>
</template>

<script lang="ts" setup>
import { addShopCar, getShopCarList } from '@/service/shop/shop'
// import radio from '@/components/radio.vue'
defineOptions({
  name: 'Shopping',
  // conponents: {
  //   radio,
  // },
})
const menuList = ref([
  {
    name: '删除商品',
  },
])
const handleChange = (e: any) => {
  countProduct()
}
const countProduct = () => {
  params.id = ''
  params.num = ''
  priceAll.value = 0
  productList.value.forEach((el: any, index: number) => {
    if (el.checked) {
      priceAll.value += el.price * el.buy_count
      params.id += el.good_id + ','
      params.num += el.buy_count + ','
    }
  })
  if (params.id) {
    params.id = params.id.slice(0, -1)
  }
  if (params.num) {
    params.num = params.num.slice(0, -1)
  }
  if (params.id.split(',').length === productList.value.length) {
    checkedAll.value = true
  } else {
    checkedAll.value = false
  }
}
const productList: Ref<any> = ref()
const checkChange = () => {
  countProduct()
}
const checkedAll = ref(false)
const handleCheckAll = (checked: any) => {
  console.log(checked)
  checkedAll.value = checked
  if (checked.value) {
    productList.value.map((m: any) => {
      m.checked = true
      return m
    })
  } else {
    productList.value.map((m: any) => {
      m.checked = false
      return m
    })
  }
  countProduct()
}
const params: any = {
  id: '',
  num: '',
}
const priceAll = ref(0)
const buyProduct = () => {
  for (let i = 0; i < productList.value.length; i++) {
    const item: any = productList.value[i]
    if (item.checked) {
      if (!item.sku_id && item.buy_count === 0) {
        uni.showToast({
          title: '请选择商品规格',
          icon: 'none',
          duration: 2000,
        })
        return
      }
    }
  }
  if (!params.id || !params.num) {
    uni.showToast({
      title: '请选择商品规格',
      icon: 'none',
      duration: 2000,
    })
    return
  }
  uni.setStorageSync('buyProduct', JSON.stringify(params))
  uni.navigateTo({
    url: '/pages/shopping/confirmOrder',
  })
}
// const headBg = ref('../../static/images/background/home-header.png')
// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()
onLoad(() => {})
onShow(() => {
  getData()
})
const getData = () => {
  getShopCarList().then((res: any) => {
    res.data.list.map((m: any) => {
      m.sku_id = null
      m.sku_name = null
      return m
    })
    productList.value = res.data.list
  })
}
const overlayShow = ref(false)
let itemId: any = null
const longPress = (id: any) => {
  itemId = id
  overlayShow.value = true
}
const openDelete = (name: string) => {
  uni.showModal({
    content: '确定删除该商品吗？',
    success: (res: any) => {
      if (res.confirm) {
        deleteProduct()
      }
    },
  })
}
const deleteProduct = () => {
  const param: any = {
    id: itemId,
    num: 0,
    type: 1,
  }
  addShopCar(param).then((res: any) => {
    getData()
  })
}
const popupShow = ref(false)
const closePopup = () => {
  popupShow.value = false
}
const productInfo = ref(null)
const scalesList = ref([])
const buyProductItem = ref(null)
const handleIndex = ref(0)
const openModel = (item: any, index: number) => {
  popupShow.value = true
  proCount.value = 0
  productInfo.value = item
  handleIndex.value = index
  scalesList.value = [
    {
      name: '规格',
      list: item.skus,
    },
  ]
  if (item.skus.length > 0) {
    buyProductItem.value = item.skus[0]
  } else {
    buyProductItem.value = []
  }
}
const selectBuyProduct = (spec: any) => {
  buyProductItem.value = spec
}
const proCount: any = ref(0)

const sureSelect = () => {
  productList.value[handleIndex.value].buy_count = proCount.value
  if (productList.value[handleIndex.value]) {
    productList.value[handleIndex.value].sku_id = buyProductItem.value.id
    productList.value[handleIndex.value].sku_name = buyProductItem.value.title
  }
  popupShow.value = false
}
</script>

<style scoped lang="scss">
.head-bg {
  position: fixed;
  top: 0;
  left: 0;
  z-index: -1;
  width: 100vw;
  height: 472rpx;
  background-position: center;
  background-size: cover;
}
.home-content {
  height: calc(100% - var(--wot-navbar-height, 88rpx));
  overflow: auto;
}
.product-card {
  padding-bottom: 32rpx;
  margin-bottom: 32rpx;
  border-bottom: 1rpx solid #f5f5f5;
}
.product-info {
  width: calc(100% - 312rpx);
  margin-left: 20rpx;
  transition: all 0.3s linear;
}
.product-info-checkbox {
  width: calc(100% - 240rpx);
}
.product-type {
  width: 208rpx;
  height: 44rpx;
  padding: 4rpx 16rpx;
  color: #666666;
  background: #f3f4f8;
  border-radius: 8rpx;
}
::v-deep .wd-button {
  width: 100% !important;
  height: 100% !important;
}
</style>
